package com.cskaoyan.market.controller.Admin;

import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.service.admin.MarketAdminService;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.shiro.mgt.SecurityManager;
import javax.servlet.http.HttpServlet;

import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/admin/profile")
public class AdminProfileController extends HttpServlet {
    @Autowired
    SecurityManager securityManager;
    @Autowired
    MarketAdminService marketAdminService ;
@PostMapping("password")
public Object changePassword(@RequestBody Map<String,String> map)  {
    String newPassword2 = map.get("newPassword2");
    String newPassword = map.get("newPassword");
    String oldPassword = map.get("oldPassword");

    BindingResult bindingResult=null;
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
    MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
    if(!Objects.equals(newPassword2, newPassword)){
            return ResponseUtil.fail(600, "两次密码不一致");
        }
    admin.setPassword(newPassword);
    MarketAdmin marketAdmin = marketAdminService.updatePassword(admin,oldPassword,bindingResult);
    if(marketAdmin!=null){
        session.removeAttribute("admin");
        return ResponseUtil.ok();
        }else {
            return ResponseUtil.fail(600, "旧密码错误");
        }
    }
}
